<?php
class ModelCatalogDiscount extends Model {
    public function getDiscount($product_id) {
        $status = TRUE;          
        $sql = "SELECT d.* FROM " . DB_PREFIX . "discount d " .
            " LEFT JOIN " . DB_PREFIX . "discount_description dc ON (d.discount_id = dc.discount_id) " .
            " LEFT JOIN " . DB_PREFIX . "discount_product dp ON (d.discount_id = dp.discount_id) " .
            " WHERE dc.language_id = '" . (int)$this->config->get('config_language_id') . "' AND dp.product_id = '" . (int)$product_id . "' AND ((date_start = '0000-00-00' OR date_start < NOW()) AND (date_end = '0000-00-00' OR date_end > NOW())) AND d.status = '1' " . 
            " ORDER BY d.priority ASC LIMIT 0,1";
        
        $discount_query = $this->db->query($sql);        
        $price = $this->getProductPrice($product_id);
            
        if ($discount_query->num_rows) {
            if($discount_query->row['type'] = 'P'){                  
                $discount = $price - $price * $discount_query->row['discount'] / 100;
            }
            else{
                $discount = $price - $discount_query->row['discount'];
            }                      
            
            return $discount;
        }
        
        return 0;
    }
    
    private function getProductPrice($product_id) { 
        $query = $this->db->query("SELECT price FROM " . DB_PREFIX . "product WHERE product_id = '" . (int)$product_id . "' AND date_available <= NOW() AND status = '1'");
    
        return isset($query->row['price']) ? $query->row['price'] : 0;
    }
}
?>